<template>
  <tm-app class="space-list-page">
    <!-- #ifndef H5 -->
    <tm-navbar :title="titleText"></tm-navbar>
    <!-- #endif -->
    <view class="space-list-page__search">
      <tm-input
        v-model="keyword"
        prefix="tmicon-search"
        clearable
        placeholder="搜索"
        @clear="clearKeyword"
      ></tm-input>
    </view>
    <scroll-view scroll-y class="space-list-page__list">
      <view
        v-for="space in filteredSpaces"
        :key="space.id"
        class="space-card"
        @click="selectSpace(space)"
      >
        <tm-avatar
          v-if="space.avatar"
          class="space-card__avatar"
          :size="72"
          :img="space.avatar"
        />
        <avatar
          v-else
          class="space-card__avatar"
          :userName="space.name"
          width="72rpx"
          height="72rpx"
          lineHeight="72rpx"
          fontSize="30rpx"
        />
        <view class="space-card__info">
          <text class="space-card__name">{{ space.name }}</text>
          <text class="space-card__desc">{{ space.remark || '暂无简介' }}</text>
        </view>
        <tm-icon
          v-if="space.id === currentSpaceId"
          name="tmicon-check"
          color="#2F88FF"
          :font-size="32"
        />
      </view>
      <view v-if="filteredSpaces.length === 0" class="space-list-page__empty">
        <tm-result :showBtn="false" title="暂无匹配单位"></tm-result>
      </view>
    </scroll-view>
  </tm-app>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref, type Ref } from 'vue'
import orgCtrl from '@/ts/controller'
import { IBelong } from '@/ts/core'
import avatar from '@/components/avatar/avatar.vue'

type SpaceOption = {
  id: string
  name: string
  avatar: string
  remark: string
}

const keyword = ref<string>('')
const currentSpaceId = ref<string>(orgCtrl.home.current.id)
const subscribeKeys = ref<string[]>([])
const spaceOptions: Ref<SpaceOption[]> = ref<SpaceOption[]>([])

const buildSpaceOption = (space: IBelong): SpaceOption => {
  return {
    id: space.id,
    name: space.name,
    avatar: space.share?.avatar?.thumbnail ?? '',
    remark: space.remark ?? space.typeName ?? ''
  }
}

const syncSpaces = (): void => {
  spaceOptions.value = orgCtrl.spaces.map(item => buildSpaceOption(item))
}

const findSpace = (spaceId: string): IBelong | undefined => {
  return orgCtrl.spaces.find(item => item.id === spaceId)
}

syncSpaces()

const filteredSpaces = computed((): SpaceOption[] => {
  const value = keyword.value.trim()
  if (value === '') {
    return spaceOptions.value
  }
  return spaceOptions.value.filter(item => {
    return item.name.includes(value) || item.remark.includes(value)
  })
})

const titleText = computed((): string => {
  return `切换单位 (${filteredSpaces.value.length})`
})

const selectSpace = async (space: SpaceOption): Promise<void> => {
  if (space.id === currentSpaceId.value) {
    uni.navigateBack()
    return
  }
  const targetSpace = findSpace(space.id)
  if (!targetSpace) {
    uni.showToast({
      title: '未找到单位',
      icon: 'none'
    })
    return
  }
  uni.showLoading({
    title: '切换中'
  })
  try {
    await orgCtrl.home.switchSpace(targetSpace)
    orgCtrl.changCallback()
    currentSpaceId.value = orgCtrl.home.current.id
    uni.showToast({
      title: '切换成功',
      icon: 'success'
    })
    uni.navigateBack()
  } catch (error) {
    uni.showToast({
      title: '切换失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

const clearKeyword = (): void => {
  keyword.value = ''
}

onMounted(() => {
  const key = orgCtrl.subscribe(() => {
    currentSpaceId.value = orgCtrl.home.current.id
    syncSpaces()
  }, false)
  subscribeKeys.value = [key]
})

onUnmounted(() => {
  if (subscribeKeys.value.length > 0) {
    orgCtrl.unsubscribe(subscribeKeys.value)
  }
})
</script>

<style lang="scss" scoped>
.space-list-page {
  min-height: 100vh;
  background-color: #f5f6fa;
  display: flex;
  flex-direction: column;
}

.space-list-page__search {
  padding: 24rpx;
}

.space-list-page__list {
  flex: 1;
  padding: 0 24rpx 24rpx;
  box-sizing: border-box;
}

.space-card {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  gap: 24rpx;
}

.space-card__avatar {
  flex-shrink: 0;
}

.space-card__info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.space-card__name {
  font-size: 30rpx;
  color: #1f2233;
  font-weight: 600;
}

.space-card__desc {
  font-size: 24rpx;
  color: #97a0b4;
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  line-clamp: 3;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.space-list-page__empty {
  margin-top: 120rpx;
}
</style>
